import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
 
public class ReadReverse{
   private static final int  BUFSIZE=8;
  public static void read(String filename) {
 
    RandomAccessFile rf = null;
    byte []readbuf=new byte[BUFSIZE*3];
    int bytestoRead;
    int tail=0;
    int i;
    try {
      rf = new RandomAccessFile(filename, "r");
      long len = rf.length();
      long start = rf.getFilePointer();
      long fpos = start + len - 1;
      int remsize=0;
      String rem=null;
      String line;
      rf.seek(fpos);
      int pcount=0;
      while (fpos > start) {
	      bytestoRead=BUFSIZE;
	      if(fpos-start<BUFSIZE){
		      bytestoRead=(int)(fpos-start);
	      }
	      fpos-=bytestoRead;
	      rf.seek(fpos);
	      rf.read(readbuf,0,bytestoRead);
	      if(remsize>0){
		      System.arraycopy(readbuf,BUFSIZE,readbuf,bytestoRead,remsize);
		      bytestoRead+=remsize;
		      remsize=0;
	      }
	      tail=bytestoRead-1;
	      while(tail>0){
		      for(i=tail-1;i>=0;i--){
			      if(readbuf[i]=='\r'||readbuf[i]=='\n'){
				  String str=new String(readbuf,i+1,tail-i);
				  if(null==rem){
					if('\n'!=str.charAt(str.length()-1)){
						str+="\n";
					}
					System.out.print(str);
				  }
				  break;
			      }
		      }
		      if(i>=0){
			tail=i;
		      }else{
			remsize=tail-i;
			System.arraycopy(readbuf,0,readbuf,BUFSIZE,tail-i);
			break;
		      }
	      }
	      
      }
      if(remsize>0){
	      System.out.print(new String(readbuf,BUFSIZE,remsize));
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (rf != null)
          rf.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
 
  public static void main(String args[]) {
    read("d:\\2.txt");
  }
}

